package cn.tedu.yushouge.pet.adopt.service.impl;


import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.pojo.vo.PageData;
import cn.tedu.yushouge.commons.web.ServiceCode;
import cn.tedu.yushouge.pet.adopt.mapper.AdoptMapper;
import cn.tedu.yushouge.pet.adopt.mapper.PetMapper;
import cn.tedu.yushouge.pet.adopt.mapper.PetPicMapper;
import cn.tedu.yushouge.pet.adopt.pojo.entity.Adopt;
import cn.tedu.yushouge.pet.adopt.pojo.entity.Pet;
import cn.tedu.yushouge.pet.adopt.pojo.entity.PetPic;
import cn.tedu.yushouge.pet.adopt.pojo.param.PetAddNewParam;
import cn.tedu.yushouge.pet.adopt.pojo.param.PetAddNewParamOfString;
import cn.tedu.yushouge.pet.adopt.pojo.param.PetUpdateInfoParam;
import cn.tedu.yushouge.pet.adopt.pojo.vo.PetListItemVO;
import cn.tedu.yushouge.pet.adopt.pojo.vo.PetStandardVO;
import cn.tedu.yushouge.pet.adopt.service.IPetService;
import cn.tedu.yushouge.commons.util.PageInfoToPageDataConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class PetServiceImpl implements IPetService {
    @Autowired
    private PetMapper petMapper;

    @Autowired
    private AdoptMapper adoptMapper;

    @Autowired
    private PetPicMapper petPicMapper;

    @Override
    public void addNew(PetAddNewParamOfString petAddNewParamOfString) {
        log.debug("开始处理【添加宠物】的业务，参数：{}", petAddNewParamOfString);

        Instant instant = Instant.parse(petAddNewParamOfString.getBirthday());
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();

        PetAddNewParam petAddNewParam = new PetAddNewParam();
        BeanUtils.copyProperties(petAddNewParamOfString,petAddNewParam);
        petAddNewParam.setBirthday(localDate);

        // 检查商品分类名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<Pet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pet_name", petAddNewParam.getPetName());
        int countByName = petMapper.selectCount(queryWrapper);
        log.debug("根据宠物名称统计匹配的宠物数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "添加宠物失败，宠物名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        // 将宠物品数据写入到数据库中
        Pet pet = new Pet();
        BeanUtils.copyProperties(petAddNewParam, pet);
        pet.setGmtCreate(LocalDateTime.now());
        pet.setGmtModified(LocalDateTime.now());
        int rows = petMapper.insert(pet);
        if (rows != 1) {
            String message = "添加宠物失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的宠物数据插入到数据库，完成！");

    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据ID删除订单】的业务，参数：{}", id);
        // 检查商品分类是否存在，如果不存在，则抛出异常
        QueryWrapper<Pet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = petMapper.deleteById(id);
        if (countById == 0) {
            String message = "删除宠物失败，该宠物不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //检查是否有adopt表关联到了此宠物，如果存在，则抛出异常
        QueryWrapper<Adopt> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("pet_id",id);
        int countByPetId2 = adoptMapper.selectCount(queryWrapper2);
        log.debug("根据宠物领养表ID统计匹配的宠物数量，结果：{}",countByPetId2);
        if (countByPetId2>0){
            String message = "删除宠物失败，仍然有宠物领养表关联到此宠物";
            log.warn(message);
            throw  new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        QueryWrapper<PetPic> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("pet_id",id);
        int countByPetId3 = petPicMapper.selectCount(queryWrapper3);
        log.debug("根据宠物图片表ID统计匹配的宠物数量，结果：{}",countByPetId2);
        if (countByPetId3>0){
            String message = "删除宠物失败，仍然有宠物图片表关联到此宠物";
            log.warn(message);
            throw  new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        int rows = petMapper.deleteById(id);
        if (rows != 1){
            String message = "删除宠物请求失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("从宠物表删除一条数据，完成！");
    }

    @Override
    public void updateInfoById(Long id, PetUpdateInfoParam petUpdateInfoParam) {
        log.debug("开始处理【根据ID修改宠物数据】的业务，参数：{}", id);
        Pet pet = new Pet();
        BeanUtils.copyProperties(petUpdateInfoParam,pet);
        pet.setId(id);
        pet.setGmtCreate(LocalDateTime.now());
        pet.setGmtModified(LocalDateTime.now());
        int rows = petMapper.updateById(pet);
        if (rows == 0) {
            String message = "修改宠物信息失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的宠物数据更新入到数据库，完成！");
    }

    @Override
    public PetStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询宠物详情】的业务，参数：{}", id);
//        // 定义格式化模式，例如 "yyyy-MM-dd" 表示年-月-日
//        String pattern = "yyyy-MM-dd";
//        // 创建 DateTimeFormatter 对象并指定格式化模式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

        PetStandardVO queryResult = petMapper.getStandardById(id);

        // 使用 DateTimeFormatter 格式化 LocalDateTime 对象为字符串
//        queryResult.setBirthday(queryResult.getBirthday().format(formatter));
        if (queryResult == null){
            String message = "查询订单详情失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<PetListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<PetListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询宠物列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<PetListItemVO> list = petMapper.list();
        PageInfo<PetListItemVO> pageInfo = new PageInfo<>(list);
        PageData<PetListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

}
